<?PHP

if ( !defined('ABSPATH') )
	define('ABSPATH', dirname(dirname(dirname(dirname(dirname(dirname(__FILE__)))))) . '/');

if(!isset($_POST['phpbb_path']) && !defined('PHPBBPATH')){
	if($path = get_option('op_module_phpbb')){
		define('PHPBBPATH',$path);	
	}
	define('PHPBBPATH','forum/');
}


// ===================================
// = House Keeping methods for phpBB =
// ===================================
class module_phpbb{
	function set_path($path){
		// validate path here
		if(!get_option('op_module_phpbb')){
			add_option('op_module_phpbb',$path);
		}
		else{
			update_option('op_module_phpbb',$path);
		}
		
		define('PHPBBPATH',$path);
	}
	
	function set_tab($tab){
		if(!get_option('op_module_phpbb_tab')){
			add_option('op_module_phpbb_tab',$tab);
		}
		else{
			update_option('op_module_phpbb_tab',$tab);
		}
	}
		
	function install(){
		$phpbb_path = attribute_escape($_POST['phpbb_path']);
		module_phpbb::set_path($phpbb_path);
		module_phpbb::set_tab(attribute_escape($_POST['phpbb_tab']));

		if(file_exists(ABSPATH.PHPBBPATH.'includes/auth/auth_op.php')){
			$helptxt = '<p>To activate OnePress in phpBB, log into the administration center for phpBB and activate the "Op" authentication method.<br/>This setting is located at: <strong>"Client Communication" &raquo; "Authentication" &raquo; "Select an authentication method" &raquo; "Op"</strong><br/>Note: Leave all fields blank and click submit to activate OP authentication.</p>';
			return array('error'=>0, 'help'=>$helptxt);
		}
		
		if(is_writable(ABSPATH.PHPBBPATH.'includes/auth')){
			copy(TEMPLATEPATH.'/phpbb/auth_op.php',ABSPATH.PHPBBPATH.'includes/auth/auth_op.php');
			$helptxt = '<p><strong>Success</strong>: The phpBB module was activated.  The OnePress authentication library has been successfully added to your phpBB install.</p>';
			$helptxt .= '<p>To activate OnePress in phpBB, log into the administration center for phpBB and activate the "Op" authentication method.<br/>This setting is located at: <strong>"Client Communication" &raquo; "Authentication" &raquo; "Select an authentication method" &raquo; "Op"</strong><br/>Note: Leave all fields blank and click submit to activate OP authentication.</p>';
			return array('error' => 0, 'help'=>$helptxt);
		}
		else{
			$helptxt = '<p><strong>Error</strong>: The phpBB module was <strong>not</strong> activated.  The OnePress authentication library was <strong>not</strong> successfully added to your phpBB install.<br/>The directory, <i>'.ABSPATH.PHPBBPATH.'includes/auth/</i>, must be writeable.<br/><br/>Upon making these changes, you may attempt to reactivate this module.<br/><br/>You may also manually copy the file located at <i>'.TEMPLATEPATH.'/phpbb/auth_op.php</i> to the destination folder.</p>';
			return array('error' => 1, 'help'=>$helptxt); // error 1 means not writeable
		}
	}
	
	function upgrade(){
		if(is_writable(ABSPATH.PHPBBPATH.'includes/auth')){
			unlink(ABSPATH.PHPBBPATH.'includes/auth/auth_op.php');
			if(copy(TEMPLATEPATH.'/phpbb/auth_op.php',ABSPATH.PHPBBPATH.'includes/auth/auth_op.php')){
				die('Upgrade Successful');
			}
			else{
				die("The directory, <i>'.ABSPATH.PHPBBPATH.'includes/auth/</i>, must be writeable.<br/><br/>Upon making these changes, you may attempt to reactivate this module.<br/><br/>You may also manually copy the file located at <i>'.TEMPLATEPATH.'/phpbb/auth_op.php</i> to the destination folder.");
			}
		}
	}
	
	function checkVersion(){
		if(!file_exists(ABSPATH.PHPBBPATH.'includes/auth/auth_op.php')) return TRUE;
		
		$in_theme = file_get_contents(TEMPLATEPATH.'/phpbb/auth_op.php');
		preg_match('/OnePress\ Version\:\s([0-9\.]+)/',$in_theme,$version);
		$latest_version = $version[1];
		
		$installed = file_get_contents(ABSPATH.PHPBBPATH.'includes/auth/auth_op.php');
		preg_match('/OnePress\ Version\:\s([0-9\.]+)/',$installed,$version);
		$installed_version = $version[1];
		
		return $installed_version == $latest_version;
	}
}

class op_phpBB3{
	var $user;
	var $loggedin;
	
	function getIdentity(){
		define('IN_PHPBB', true);
		global $phpbb_root_path;
		global $phpEx;
		
		$phpbb_root_path = ABSPATH.PHPBBPATH;

		$phpEx = substr(strrchr(__FILE__, '.'), 1);
		
		// Start session management
		global $user;
		global $auth;
		global $template;
		global $cache;
		global $db;
		global $config;
		
		// Hack to fix declaration of make_clickable
		$include_contents = file_get_contents($phpbb_root_path . 'common.' . $phpEx);
		$include_contents = str_replace('<?php','',$include_contents);
		$include_contents = str_replace('?>','',$include_contents);
		$include_contents = str_replace('require($phpbb_root_path . \'includes/functions_content.\' . $phpEx);','',$include_contents);
		eval($include_contents);
		
		$user->session_begin();
		$auth->acl($user->data);
		$user->setup();
		
		if($user->data['is_registered'] == TRUE){
			$identity = array(
				'id'		=>	$user->data['user_id'],
				'alias'	=>	$user->data['username_clean'],
				'email'	=>	$user->data['user_email'],
				'rank'	=>	$user->rank['user_rank']
			);
		}
		else{
			$identity = array();
		}
	}
	
	function login(){
		define('IN_PHPBB',TRUE);
		
		global $op_credentials;
		global $auth;
		
		$username = $op_credentials['username']=='' ? request_var('username', '', true) : $op_credentials['username'];
		$password = $op_credentials['password']=='' ? request_var('password', '', true) : $op_credentials['password'];
		
		$result = $auth->login($username, $password);
		
		return $result['status'] == LOGIN_SUCCESS ? array('response'=>TRUE,'error'=>'') : array('response'=>FALSE,'error'=>(!$config['board_contact']) ? sprintf($user->lang[$result['error_msg']], '', '') : sprintf($user->lang[$result['error_msg']], '<a href="mailto:' . htmlspecialchars($config['board_contact']) . '">', '</a>'));
	}
	
	function logout(){
		global $user;
		global $auth;
		
		$user->session_kill();
		$user->session_begin();
	}
	
	function changePassword($username,$password){
		$phpbb_root_path = ABSPATH.PHPBBPATH;

		require($phpbb_root_path.'config.php');
		
		$dbr = mysql_connect($dbhost,$dbuser,$dbpasswd);
		mysql_select_db($dbname);
		define('USERS_TABLE', $table_prefix . 'users');
		
		// set user_pass_convert to 1 so user's pass will be hashed under phpBB rules when logging in after pass is changed in WordPress
		$sql = 'UPDATE ' . USERS_TABLE . ' SET user_password="'.md5($password).'",user_pass_convert=1 WHERE username = "' . $username . '"';
		$result = mysql_query($sql);
	}
	
	function changeEmail($username,$email){
		$phpbb_root_path = ABSPATH.PHPBBPATH;

		require($phpbb_root_path.'config.php');
		
		$dbr = mysql_connect($dbhost,$dbuser,$dbpasswd);
		mysql_select_db($dbname);
		define('USERS_TABLE', $table_prefix . 'users');
		
		$sql = 'UPDATE ' . USERS_TABLE . ' SET user_email="'.$email.'" WHERE username = "' . $username . '"';
		$result = mysql_query($sql);
	}
	
	function getRecentPosts($sortby){
		global $phpbb_root_path,$phpEx;
		$phpbb_root_path = PHPBBPATH;
		$phpEx = 'php';
		define('IN_PHPBB',TRUE);
		include(ABSPATH.PHPBBPATH.'config.php');
		include(ABSPATH.PHPBBPATH.'includes/constants.php');
		include(ABSPATH.PHPBBPATH.'includes/functions_display.php');
		$db = mysql_connect($dbhost,$dbuser,$dbpasswd);
		mysql_select_db($dbname, $db); // being in different databases cause problems
		
		/** These can all be widget options **/
		// Order by 
		// topic_last_post_id (Default)
		// topic_replies 
		// topic_views 
		
		//$sortby = 'topic_last_post_id'; // get from widget options
		$numberoftopics = 5; // get from widget options

		// 0 => users can see all topics including authorized issue(but they cant read the posts) 
		// 1 => users can see only authorized topics 
		$authneeded = 1; 
		
		/** End -- These can all be widget options **/
		
		$auth_forum_ary_top5 = array();
		// Get forum info 
		$sql = "SELECT forum_id FROM " . FORUMS_TABLE;
		
		$result = mysql_query($sql,$db);
		// Authorized forums info 
		while( $forum_row = mysql_fetch_assoc($result))
		{
			if( $is_auth_ary_top5[$forum_row['forum_id']]['auth_read'] == 1)
			{
				array_push($auth_forum_ary_top5, $forum_row['forum_id']);
			}
		}
	
		if( count($auth_forum_ary_top5) == 0 || !$authneeded )
		{
			$auth_forums_top5 = "";
		}
		else
		{
			$auth_forums_top5 = 'AND f.forum_id IN('; 
			$auth_forums_top5 .= count($auth_forum_ary_top5) > 1 ? implode (',', $auth_forum_ary_top5) : $auth_forum_ary_top5[0];
			$auth_forums_top5 .= ')';
		}
		
		$sql = "SELECT topic_id, topic_title, topic_poster, topic_views, topic_replies, f.forum_id, forum_name
		FROM " . TOPICS_TABLE . " t JOIN " . FORUMS_TABLE . " f
		ON t.forum_id = f.forum_id
		WHERE topic_moved_id = '0'
		$auth_forums_top5
		ORDER BY $sortby DESC LIMIT 0, $numberoftopics";
		
		$result = mysql_query($sql,$db); 
	
		$values = array();
		
		$c_sql = 'SELECT config_value FROM '.CONFIG_TABLE.' WHERE config_name="avatar_path"';
		$c_result = mysql_query($c_sql,$db);
		$c_row = mysql_fetch_assoc($c_result);
			
		while( $rows = mysql_fetch_assoc($result) )
		{
			$topic_url = '/'.PHPBBPATH."viewtopic.php?t=" . $rows['topic_id']; 
			$forum_url = '/'.PHPBBPATH."viewforum.php?f=" . $rows['forum_id']; 
	
			$topic_poster = $rows['topic_poster']; 
			$topic_last_post_id = $rows['topic_last_post_id']; 
	
			$sql = "SELECT post_username, user_id, username 
			FROM " . POSTS_TABLE . ", " . USERS_TABLE . " 
			WHERE topic_id = '" . $rows['topic_id'] . "' 
			AND poster_id = user_id 
			ORDER BY post_id LIMIT 0, 1"; 
			
			$p_result = mysql_query($sql,$db); 
			$p_row = mysql_fetch_assoc($p_result);
	
			$poster_name = ( $topic_poster != ANONYMOUS ) ? $p_row['username'] : ( !$p_row['post_username'] ? $lang['Guest'] : $p_row['post_username']);
			$poster_url = ( $topic_poster != ANONYMOUS && !$p_row['post_username'] ) ? '/'.PHPBBPATH.'memberlist.php?mode=viewprofile&u='.$topic_poster : '';

			$last_post_url = '/'.PHPBBPATH."viewtopic.$phpEx?p=$topic_last_post_id#$topic_last_post_id";
			
			$u_sql = 'SELECT user_avatar,user_avatar_type,user_avatar_width,user_avatar_height FROM '.USERS_TABLE.' WHERE user_id="'.$p_row['user_id'].'"';
			$u_result = mysql_query($u_sql,$db);
			$u_row = mysql_fetch_assoc($u_result);

			$avatar = get_user_avatar($u_row['user_avatar'], $u_row['user_avatar_type'], $u_row['user_avatar_width'], $u_row['user_avatar_height']);
			
			$values[] = array( 
				'forum_name' => $rows['forum_name'],
				'forum_url' => $forum_url,
				'topic' => $rows['topic_title'],
				'topic_url' => $topic_url,
				'topic_views' => $rows['topic_views'],
				'topic_replies' => $rows['topic_replies'],
				'time' => $r_row['post_time'],
				'author' => $poster_name,
				'author_link' => $poster_url,
				'last_post' => $last_post_url,
				'avatar' => $avatar
			);
		}
		
		mysql_select_db(DB_NAME); // being in different databases cause problems
		return $values;
	}
	
	function addUser($user){
		global $phpbb_root_path,$phpEx;
		
		// Use the user_add function, this code is from auth.php line 864-869
		if (!function_exists('user_add'))
		{
			include($phpbb_root_path . 'includes/functions_user.' . $phpEx);
		}

		return user_add($user);
	}
	
	function getUserById($id){
		global $db;
		mysql_select_db($db->dbname);
		
		$sql = 'SELECT user_id, username, user_password, user_passchg, user_pass_convert, user_email, user_type, user_login_attempts
			FROM ' . USERS_TABLE . "
			WHERE user_id = '" . $id . "'";
		
		$result = $db->sql_query($sql);
		$user = $db->sql_fetchrow($result);
		$db->sql_freeresult($result);
		return $user;
	}
	
	function getUserByName($name){
		$phpbb_root_path = ABSPATH.PHPBBPATH;

		require($phpbb_root_path.'config.php');
		
		$dbr = mysql_connect($dbhost,$dbuser,$dbpasswd);
		mysql_select_db($dbname);
		define('USERS_TABLE', $table_prefix . 'users');
		
		$sql = 'SELECT user_id, username, user_password, user_passchg, user_pass_convert, user_email, user_type, user_login_attempts
			FROM ' . USERS_TABLE . "
			WHERE username = '" . $name . "'";
		
		$result = mysql_query($sql);
		$user = mysql_fetch_row($result);
		mysql_free_result($result);
		
		return $user;
	}
}

?>